package com.dwj.auto.comment.config.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName TrimArgFilter
 * @Description 空白字符串参数过滤器
 * @Author dwjian
 * @Date 2020/1/30 17:29
 */
@WebFilter(filterName = "trimArgFilter", urlPatterns = "/*")
public class TrimArgFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(new TrimArgHandler((HttpServletRequest) servletRequest), servletResponse);
    }

    /**
     * 空白参数处理器
     */
    class TrimArgHandler extends HttpServletRequestWrapper {

        private Map<String, String[]> params = new HashMap<>();

        public TrimArgHandler(HttpServletRequest request) {
            // 将request交给父类，以便于调用对应方法的时候，将其输出，其实父亲类的实现方式和第一种new的方式类似
            super(request);
            //将参数表，赋予给当前的Map以便于持有request中的参数
            Map<String, String[]> requestMap = request.getParameterMap();
            this.params.putAll(requestMap);
            this.modifyParameterValues();
        }

        /**
         * 将parameter的值去除空后重写回去
         */
        public void modifyParameterValues() {
            Set<Map.Entry<String, String[]>> paramSet = params.entrySet().stream().filter(e -> StringUtils.isNotEmpty(e.getValue()[0])).collect(Collectors.toSet());
            Map<String, String[]> map = new HashMap<>();
            for (Map.Entry<String, String[]> entry : paramSet) {
                (entry.getValue())[0] = (entry.getValue())[0].trim();
                map.put(entry.getKey(), entry.getValue());
            }
            params = map;
        }

        /**
         * 重写getParameter 参数从当前类中的map获取
         */
        @Override
        public String getParameter(String name) {
            String[] values = params.get(name);
            if (values == null || values.length == 0) {
                return null;
            }
            return values[0];
        }

        /**
         * 重写getParameterValues
         */
        @Override
        public String[] getParameterValues(String name) {
            return params.get(name);
        }
    }
}
